<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import Header from '@/components/Header.vue'
import VideoPlayer from '@/components/VideoPlayer.vue'
import VideoManageDialog from '@/components/VideoManageDialog.vue'
import { useUserStore } from '@/store/userStore'
import WebSocketService from '@/utils/websocket'

const currentArea = ref({
  name: '中国',
  code: '',
  level: 0
})
const userStore = useUserStore()
const stationConfig = computed(() => userStore.stationConfig)
const ScreenTitle = computed(() => {
  let title = stationConfig.value?.VideoText
  //TitleType: "区域+固定文字"
  if (stationConfig.value?.TitleType === '区域+固定文字') {
    title = `${currentArea.value.name}${title}`
    //将中国替换为全国
    title = title.replace('中国', '全国')
    //如果currentArea.level为4，说明是子节点，直接显示子节点名称
    if (currentArea.value.level === 4) {
      title = `${currentArea.value.name}`
    }
  } else {
    title = stationConfig.value.VideoTitle
  }
  return title
})

// 获取视频元素配置列表
const videoEleList = computed(() => {
  return stationConfig.value?.D001729StationConfigVideoEle || []
})

// 处理区域树变化
const handleTreeChange = (params: any) => {
  console.log(params, '==params==')
  currentArea.value = { ...params }
  let regionCode = params.value
  console.log(regionCode, '==regionCode==')
  videoPlayerRef.value.filterCurrentRegionList(regionCode)
  if (!params || params.level === 1) {
    currentArea.value.name = '全国'
    currentArea.value.code = ''
    currentArea.value.level = 1
    userStore.userInfo.powerCode = 'admin'
    userStore.setSelectedAreaCode('')
    userStore.fetchStationConfig()
    return
  }
  if ([2, 3].includes(params.level)) {
    userStore.userInfo.powerCode = 'childrenOrg'
    userStore.setSelectedAreaCode(params.value)
    userStore.fetchStationConfig()
    return
  }
}

const powerCode = computed(() => userStore.userInfo?.powerCode)

// 处理刷新
const handleRefresh = () => {
  // 调用VideoPlayer组件的刷新方法
  videoPlayerRef.value?.refreshCameras(true)
}

// WebSocket连接实例
const wsService = ref<WebSocketService | null>(null)
const videoPlayerRef = ref()

// 处理WebSocket消息
const handleWsMessage = (event: any) => {
  try {
    if (event.type === 'eventData') {
      // console.log('收到WebSocket eventData消息:', event.data, stationConfig.value)
      // 将数据传递给VideoPlayer组件处理
      videoPlayerRef.value?.processSensorData(event.data)
    }
  } catch (error) {
    console.error('处理WebSocket消息错误:', error)
  }
}

// 初始化WebSocket连接
const initWebSocket = () => {
  // 如果已存在连接，直接返回
  if (wsService.value) {
    return
  }

  // 创建新连接
  wsService.value = new WebSocketService({
    onMessage: handleWsMessage,
    onOpen: (event) => {
      console.log('Video组件: WebSocket连接已打开', event)
    },
    onError: (event) => {
      console.error('Video组件: WebSocket连接错误', event)
    },
    onClose: (event) => {
      console.log('Video组件: WebSocket连接已关闭', event)
    }
  })

  // 建立连接
  wsService.value.connect()
}

const showVideoManageDialog = ref(false)

const handleVideoManageRefresh = () => {
  //刷新父组件
  handleRefresh()
}

const handleOpenVideoManage = () => {
  showVideoManageDialog.value = true
}

// 组件挂载时初始化
onMounted(() => {
  window.document.title = '实时视频预览'
  setTimeout(() => {
    // 初始化WebSocket连接
    initWebSocket()
  }, 5000)
})

// 组件卸载时清理
onUnmounted(() => {
  // 关闭WebSocket连接
  if (wsService.value) {
    wsService.value.disconnect()
    wsService.value = null
  }
})
</script>

<template>
  <div class="video-container">
    <Header :title="ScreenTitle" :hasTree="false" :TextFontSize="stationConfig.TextFontSize" :hasVideo="true" @treeChange="handleTreeChange" @open-video-manage="handleOpenVideoManage" />
    
    <!-- 使用封装的VideoPlayer组件 -->
    <div class="video-player-container">
      <VideoPlayer
        v-if="videoEleList && videoEleList.length > 0"
        ref="videoPlayerRef"
        :videoEleList="videoEleList"
        :handleWsMessage="handleWsMessage"
        @refresh="handleRefresh"
        :powerCode="powerCode"
      />
    </div>

    <VideoManageDialog v-model="showVideoManageDialog" @refresh="handleVideoManageRefresh" />

  </div>
</template>

<style scoped lang="scss">
.video-container {
  width: 100%;
  height: calc(100vh);
  padding: 0;
  box-sizing: border-box;
  background: linear-gradient(to top, rgba(8, 23, 46, 1), rgba(24, 70, 141, 1));
  position: relative;
  z-index: 10;
}
.video-player-container {
  position: relative;
  height: calc(100vh - 58px);
  padding-top: 48px;
}
</style>